﻿//## Microsoft Reciprocal License (Ms-RL)
//##
//## This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
//##
//## 1. Definitions
//##
//## The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
//##
//## A "contribution" is the original software, or any additions or changes to the software.
//##
//## A "contributor" is any person that distributes its contribution under this license.
//## 
//## "Licensed patents" are a contributor's patent claims that read directly on its contribution.
//## 
//## 2. Grant of Rights
//## 
//## (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
//## 
//## (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
//## 
//## 3. Conditions and Limitations
//## 
//## (A) Reciprocal Grants- For any file you distribute that contains code from the software (in source code or binary format), you must provide recipients the source code to that file along with a copy of this license, which license will govern that file. You may license other files that are entirely your own work and do not contain code from the software under any terms you choose.
//## 
//## (B) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
//## 
//## (C) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
//## 
//## (D) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
//## 
//## (E) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
//## 
//## (F) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.  

//Written by Fabian Figueredo
//http://oberdata.com.ar info@fabianfigueredo.com.ar

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using AFDS.DataAccess.Providers;
using AFDS.BusinessLogic.Comparators;
using AFDS.BusinessLogic;
using AFDS.Core.Base;
using AFDS.Core;

namespace AFDS.BusinessLogic.Helpers
{
    public class CategoryHelper : HelperBase<CategoryHelper, Category>, IDisposable
    {
        public override Category Select(Guid id)
        {            
            return (Category)ProxyProvider.SelectCategory(id);
        }

        public override void Insert(Category item)
        {
            ProxyProvider.InsertCategory(item);
        }

        public override void Update(Category item)
        {
            if (Exist(item))
            {
                ProxyProvider.UpdateCategory(item);
            }
            else
            {
                Insert(item);
            }
        }

        public override void Delete(Category item)
        {
            if (hasSites(item))
                throw new
                    AFDSException(AFDS.Core.SeverityLevel.Information,
                    LogLevel.Debug,
                    "You cannot delete a category that has sites",
                    ErrType.DeleteCategoryHasSites);

            if (hasChilds(item))
                throw new
                    AFDSException(AFDS.Core.SeverityLevel.Information,
                    LogLevel.Debug,
                    "You cannot delete a category that is parent",
                    ErrType.DeleteCategoryHasChilds);

            if (isRoot(item))
                throw new
                    AFDSException(AFDS.Core.SeverityLevel.Information,
                    LogLevel.Debug,
                    "You cannot delete a category that is a root category",
                    ErrType.DeleteCategoryIsRoot);            

            ProxyProvider.DeleteCategory(item);
        }

        public override List<Category> GetAll()
        {
            string folder = AFDS.DataAccess.Utils.StorageLocationMapPath() + "Categories" + "/";
            List<Category> categories = new List<Category>();

            foreach (string file in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly))
            {
                FileInfo info = new FileInfo(file);
                string id = info.Name.Replace(".xml", string.Empty);

                Category category = base.Load(new Guid(id));

                categories.Add(category);
            }
            return categories;
        }


        public List<Category> GetAll(bool allowSites)
        {
            List<Category> categories = new List<Category>();
            if (allowSites) categories = CategoriesAllowSites;
            else categories = CategoriesNotAllowSites;

            return categories;
        }

        public List<Category> CategoriesAllowSites
        {
            get
            {
                List<Category> i = GetAll();

                return i.FindAll(
                    delegate(Category obj)
                    {
                        return obj.AllowSites;
                    }
                );
            }
        }

        public List<Category> CategoriesNotAllowSites
        {
            get
            {
                List<Category> i = GetAll();

                return i.FindAll(
                    delegate(Category obj)
                    {
                        return !obj.AllowSites;
                    }
                );
            }
        }

        public bool isRoot(Category category) {
            using (Helpers.CategoryHelper cHelper = new CategoryHelper()) {
                if (cHelper.GetRootCategory().Id == category.Id)
                    return true;
                else
                    return false;
            }
        }


        public bool hasSites(Category category) {
            using (Helpers.SiteHelper sHelper = new SiteHelper()) {
                List<Site> items = sHelper.GetSitesByCategory(category as ICategory);
                if (items == null || items.Count < 1)
                    return false;
                else
                    return true;
            }        
        }

        public bool hasChilds(Category category) {
            List<Category> items = this.GetCategoriesByParentId(category.Id);
            if (items == null || items.Count < 1)
                return false;
            else
                return true;
        }


        public List<Category> GetCategoriesByParentId(Guid ParentId)
        {
            return GetAll().FindAll(
                c => c.ParentId == ParentId && c.Id != ParentId
            );
        }

        public List<Category> GetCategoriesByParentId(Guid ParentId, bool allowSites)
        {
            List<Category> categories = GetCategoriesByParentId(ParentId);
            if (allowSites)
                return categories.FindAll(c => c.Enable == true && c.AllowSites == true);

            return categories;
        }

        public List<Category> GetCategoriesByRoot(Guid RootId)
        {
            return GetAll().FindAll(
                delegate(Category obj)
                {
                    return obj.ParentId == RootId || obj.Id == RootId;
                }
            );
        }

        public string GetFriendlyURLPath(Category category)
        {
            return AFDSHelper.VirtualPathAbsolute  + "category/" + category.Slug + ".aspx";
        }

        public string GetFriendlyURLPath(Guid categoryid)
        {
            Category cat = Load(categoryid);
            return GetFriendlyURLPath(cat);
        }
        public string GetFriendlyURLPath(string categoryid)
        {
            Guid id = new Guid(categoryid);
            return GetFriendlyURLPath(id);
        }
        public string GetURLPath(string categoryid)
        {
            Guid id = new Guid(categoryid);
            return GetURLPath(id);
        }
        public string GetURLPath(Guid categoryid)
        {
            Category cat = Load(categoryid);
            return GetURLPath(cat);
        }

        public string GetURLPath(Category category)
        {
            return AFDSHelper.VirtualPathAbsolute + "viewcat.aspx?id=" + category.Id.ToString();
        }

        public Category GetCategoryBySlug(string slug)
        {
            List<Category> cats = GetAll().FindAll(
                delegate(Category obj)
                {
                    return obj.Slug.ToUpper() == slug.ToUpper();
                }
            );
            if (cats.Count < 1)
            {
                throw (new Exception("Data Integrity Error in GetCategoryBySlug Method"));
            }
            return cats[0];
        }

        public bool Exist(Category c)
        {
            Category cat = GetCategoryByID(c.Id);
            if (cat == null) return false;

            return true;
        }


        public Category CreateRootCategory() {
            return CreateRootCategory("Home", "home", true, false);
        }

        public Category CreateRootCategory(string rootName, string slug, bool enable, bool allowsites) {
            Category root = new Category();
            root.Id = Guid.NewGuid();
            root.Name = rootName;
            root.Slug = slug;
            root.Enable = enable;
            root.AllowSites = allowsites;
            this.Insert(root);
            AFDSHelper.SetRootCategory(root);
            return root;        
        }

        public Category GetCategoryByID(Guid id)
        {
            return GetAll().FirstOrDefault(c => c.Id == id);
        }


        public List<Category> GetAllOrderByParent(SortFactor sortType)
        {
            CategoryComparer cComparer =
                new CategoryComparer(sortType, OrderBy.ParentName);
            List<Category> c = GetAll();
            c.Sort(cComparer);
            return c;
        }

        public List<Category> GetAllOrderByParent(SortFactor sortType, bool allow)
        {
            CategoryComparer cComparer =
                new CategoryComparer(sortType, OrderBy.ParentName);


            List<Category> c;
            if (allow) c = this.CategoriesAllowSites;
            else c = GetAll();

            c.Sort(cComparer);
            return c;
        }

        public void GetCategoriesPathTree(ref ArrayList o, string i, Guid parentId, bool onlyEnabledCategories, bool addRoot, string currentId)
        {
            List<Category> categories = this.GetCategoriesByParentId(parentId);
            Category root = AFDSHelper.GetRootCategory();
            Category parent = this.GetCategoryByID(parentId);

            bool addParent = true;

            if (parent.Enable == true && parent.AllowSites == true && onlyEnabledCategories) addParent = true;
            else addParent = false;

            if (addRoot && root.Id == parent.Id) addParent = true;

            if (!addRoot && root.Id == parent.Id && parent.Enable == false) addParent = false;

            if (string.IsNullOrEmpty(currentId) || (!string.IsNullOrEmpty(currentId) && currentId != parent.Id.ToString())) {

                if (addParent) {
                    if (o.Count == 0) {
                        o.Add(
                            i + parent.Name + " > " +
                            "|" + parent.Id.ToString());
                    }
                }
            }

            string p = "";
            foreach (Category c in categories) {
                if (string.IsNullOrEmpty(currentId) || (!string.IsNullOrEmpty(currentId) && c.Id.ToString() != currentId && c.ParentId.ToString() != currentId)) {
                    p = i + c.Name + " > ";
                    if (onlyEnabledCategories) {
                        if (c.Enable == true && c.AllowSites == true)
                            o.Add(p + "|" + c.Id.ToString());
                    } else {
                        o.Add(p + "|" + c.Id.ToString());
                    }                    
                }
                GetCategoriesPathTree(ref o, p, c.Id, onlyEnabledCategories, addRoot, currentId);

            }            
        }

        public Category GetRootCategory()
        {
            try {
                SettingHelper setthl = new SettingHelper();
                Guid RootId = new Guid(setthl.GetAll()["Rootcategory"].ToString());
                return this.Load(RootId);
            } 
            catch {
                throw new AFDSException(
                    SeverityLevel.Critical, 
                    LogLevel.Debug, 
                    "Not found a root category", 
                    ErrType.NotFoundRootCategory);
            }
        }


        #region IDisposable Members

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
